import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path"; // 需要引入 path 模块

export default ({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), "");
  return defineConfig({
    plugins: [vue()],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
        "#": path.resolve(__dirname, "./assets"),
      },
      // 配置代理
      server: {
        proxy: {
          [env.VITE_API_BASE_URL]: {
            target: env.VITE_API_BASE_URL, // 使用环境变量
            changeOrigin: true,
            rewrite: (path) => path.replace(new RegExp(`^${env.VITE_API_BASE_URL}`), ""),
            bypass(req, res, options) {
              const proxyUrl =
                new URL(options.rewrite(req.url) || "", options.target).href ||
                "";
              console.log(proxyUrl);
              req.headers["x-req-proxyUrl"] = proxyUrl;
              res.setHeader("x-res-proxyUrl", proxyUrl);
            },
          },
        },
      },
    },
  });
};
